package com.ktjiaoyu.crm.config.shiro;

import com.ktjiaoyu.crm.pojo.User;
import com.ktjiaoyu.crm.service.RightService;
import com.ktjiaoyu.crm.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * 自定义Realm
 */
public class MyShiroRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Autowired
    private RightService rightService;

    /**
     * 授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("调用doGetAuthorizationInfo()获取权限信息..........");
        //获取权限信息
        User user = (User)principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //静态授权：授予Subject(用户)相应角色权限
        info.addRole(user.getRole().getRoleName());
        //Shiro动态授权：从数据库中查询该用户拥有的权限
        Set<String> rights = rightService.findRightsByRoleName(user.getRole().getRoleId());
        info.addStringPermissions(rights);
        //Shiro静态授权
        //info.addStringPermission("用户列表");   //所有用户拥有"用户列表"权限
        //info.addStringPermission("用户添加");
//        if("管理员".equals(user.getRole().getRoleName())){ //管理员拥有所有权限
//            info.addStringPermission("用户编辑");
//            info.addStringPermission("用户删除");
//        }
        return info;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("调用doGetAuthenticationInfo()获取身份信息..........");
        //获取身份信息
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //获取token中的用户名
        String username = token.getUsername();
        //根据用户名调用用户信息
        User user = userService.getUesrByName(username);
        if(user == null) throw new UnknownAccountException();   //账号错误
        if(user.getUsrFlag()==null || user.getUsrFlag().intValue()==0) throw new LockedAccountException(); //账号被锁定
        //principal：身份
        //credentials：凭证
        //realmName：当前Realm的名称
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,user.getUsrPassword(),getName());

        return info;
    }
}
